<template>
	<div v-if="user" v-my-directive data-title="用户中心" class="usermain">
		<!-- 左边 -->
		<userleft></userleft>
		<div class="CatalogLayout">
			<!-- 引入文件的方式 -->
			<div class="Genericpadding bold">我的账户</div>

			<div class="Genericpadding articlebt">
				<div class="Horizontalspacing interval">
					<div class="avatar">
						<el-avatar class="center" :size="60" :src="form.Avatar" />
					</div>

					<div class="ThinLineLayout">
						<div class="bold">{{ user.username }}</div>
						<div class="center minfont grey">建议尺寸: 100×100px，支持: .jpg、.gif、.png格式的图片，图片大小请不要超过500kb</div>
					</div>
				</div>
				<el-upload class="upload-demo center" :http-request="Pictures" action="#" :show-file-list="false" :before-upload="handleBeforeUpload">
					<el-button type="primary">上传头像</el-button>
				</el-upload>
			</div>
			<div class="Genericpadding bold helf">
				<el-form v-if="form" :rules="rules" ref="form" class="setting" :model="form" label-width="80px">
					<el-form-item class="left" label="绑定gitub">
						<el-button type="danger" @click="loginWithGitHub()" :loading="loadinggit">{{ user.githubid ? '更改github' : '绑定github' }}</el-button>
					</el-form-item>
					<el-form-item class="left" label="绑定钱包">
						<el-button type="danger" @click="getWalletSignature()" :loading="loadingadd">{{ user.address ? '更换钱包' : '绑定钱包' }}</el-button>
					</el-form-item>
					<el-form-item label="用户名">
						<el-input v-model="form.username" :disabled="true"></el-input>
					</el-form-item>
					<el-form-item label="用户组">
						<el-input v-model="form.name" :disabled="true"></el-input>
					</el-form-item>
					<el-form-item label="邮箱账号">
						<el-input v-model="form.email" :disabled="true"></el-input>
					</el-form-item>
					<el-form-item label="注册时间">
						<el-input v-model="form.Creationtime" :disabled="true"></el-input>
					</el-form-item>
					<el-form-item label="用户昵称" prop="nickname">
						<el-input v-model="form.nickname" placeholder="请输入昵称"></el-input>
					</el-form-item>
					<el-form-item label="QQ号码" prop="QQ">
						<el-input v-model="form.QQ" placeholder="请输入联系qq"></el-input>
					</el-form-item>
					<el-form-item label="微信号码" prop="WeChat">
						<el-input v-model="form.WeChat" placeholder="请输入微信"></el-input>
					</el-form-item>
					<el-form-item label="telegram" prop="telegram">
						<el-input v-model="form.telegram" placeholder="请输入telegram"></el-input>
					</el-form-item>
					<el-form-item label="个性签名">
						<el-input resize="none" type="textarea" placeholder="请输入个性签名" v-model="form.signature" :autosize="{ minRows: 2, maxRows: 2 }" maxlength="30" show-word-limit> </el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="submitForm('form')">提交</el-button>
					</el-form-item>
				</el-form>
			</div>
		</div>
	</div>
</template>
<script>
	import { ethers } from 'ethers'
	import userleft from './../components/userleft'
	import { dataRequest as api, filesRequest, automaticLogin } from '@/api/api'
	import { mapState } from 'vuex'
	export default {
		name: 'name',
		computed: {
			...mapState(['logon', 'user']),
			mapboxMap1() {
				// return this.$store.state.mapbox.map;

				return this.user
			},
		},
		components: {
			// 组件
			userleft,
		},
		data() {
			return {
				loadinggit: false,
				loadingadd: false,
				//返回值
				form: '',
				rules: {
					nickname: [
						{ required: false, message: '请输入昵称', trigger: 'blur' },
						{ min: 3, max: 16, message: '长度在 3 到 16个字符', trigger: 'blur' },
					],
					QQ: [
						{ required: false, message: '请输入QQ号码', trigger: 'blur' },
						{ validator: this.validateQQ, trigger: 'blur' },
					],
					WeChat: [
						{ required: false, message: '请输入微信号码', trigger: 'blur' },
						{ validator: this.validateWeChat, trigger: 'blur' },
					],
					telegram: [
						{ required: false, message: '请输入Telegram号码', trigger: 'blur' },
						{ validator: this.validateTelegram, trigger: 'blur' },
					],
				},
			}
		},
		methods: {
			// 函数
			handleBeforeUpload(file) {
				const maxSize = 500 * 1024 // 500 KB in bytes
				if (file.size > maxSize) {
					this.$message.error('文件大小超过限制（最大 500 KB）')
					return false // 阻止上传
				}

				const allowedExtensions = ['jpg', 'jpeg', 'png', 'gif']
				const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif']

				const fileExtension = file.name.split('.').pop().toLowerCase()
				const fileType = file.type.toLowerCase()

				if (!allowedExtensions.includes(fileExtension) || !allowedMimeTypes.includes(fileType)) {
					this.$message.error('不支持的文件类型')
					return false // 阻止上传
				}

				return true // 允许上传
			},
			async Pictures(obj) {
				console.log(obj)
				var formData = new FormData()
				formData.append('file', obj.file)

				let arr = await filesRequest(['pictureupload', formData])
				if (arr.code == 200) {
					// 重新获取用户信息
					await automaticLogin()
					this.$message.success(arr.massage)
				} else {
					this.$message.error(arr.massage)
				}
			},

			async submitForm(formName) {
				this.$refs[formName].validate(async valid => {
					if (valid) {
						// 这里提交
						let arr = { nickname: this.form.nickname, QQ: this.form.QQ, WeChat: this.form.WeChat, telegram: this.form.telegram, signature: this.form.signature }
						arr = await api(['Datamodification', arr])
						if (arr.code == 909 || arr.code == 4004) {
							this.$message.error('数据为空')
						} else if (arr.code == 200) {
							this.$message.success('修改成功')
							await automaticLogin()
						} else {
							this.$message.error('修改失败')
						}
						console.log(arr)
					} else {
						// 这里是验证不通过
						console.log('error submit!!')
						return false
					}
				})
			},
			// 验证
			validateQQ(rule, value, callback) {
				if (!value) {
					// 允许字段为空，直接通过验证
					callback()
				} else {
					const regExp = /^[1-9]\d{5,13}$/
					if (regExp.test(value)) {
						callback()
					} else {
						callback(new Error('必须为有效的QQ号码，长度在5到13个字符'))
					}
				}
			},
			validateWeChat(rule, value, callback) {
				if (!value) {
					// 允许字段为空，直接通过验证
					callback()
				} else {
					// 微信号码正则表达式，以字母开头，长度在6到20个字符之间
					const regExp = /^[a-zA-Z][a-zA-Z0-9_-]{5,19}$/
					if (regExp.test(value)) {
						callback()
					} else {
						callback(new Error('必须为有效的微信号码，以字母开头，长度在6到20个字符之间'))
					}
				}
			},
			validateTelegram(rule, value, callback) {
				if (!value) {
					// 允许字段为空，直接通过验证
					callback()
				} else {
					// Telegram号码正则表达式，以字母开头，长度在5到32个字符之间
					const regExp = /^[a-zA-Z][a-zA-Z0-9_-]{4,31}$/
					if (regExp.test(value)) {
						callback()
					} else {
						callback(new Error('必须为有效的Telegram号码，以字母开头，长度在5到32个字符之间'))
					}
				}
			},
			// 绑定gitub
			loginWithGitHub() {
				this.loadinggit = true

				const currentPath = this.$route.path
				const client_id = '0282aacf69050a9690fb'
				const redirect_uri = `http://localhost:8080/login?path=${currentPath}`
				const scope = 'user' // 请求的权限范围
				const oauthUrl = `https://github.com/login/oauth/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}&scope=${scope}`
				// 重定向至 GitHub OAuth 授权页面
				window.location.href = oauthUrl
			},
			async connectWallet() {
				if (window.ethereum) {
					try {
						await window.ethereum.request({ method: 'eth_requestAccounts' })
						const provider = new ethers.BrowserProvider(window.ethereum)
						// console.log(await provider.getSigner())
						return provider
					} catch (error) {
						this.$message.error('链接钱包失败')
					}
				} else {
					this.$message.error('请安装 MetaMask 或其他支持的钱包')
				}
			},
			// 获取钱包签名
			async getWalletSignature() {
				this.loadingadd = true
				const walletProvider = await this.connectWallet()
				if (walletProvider) {
					// 这个通过后端获取
					const message = `绑定账户:${this.user.username}` // 替换为您要签名的消息
					try {
						const signer = await walletProvider.getSigner()

						const signature = await signer.signMessage(message)
						console.log(signature)
						// 把签名结果发送到后端
						const recoveredAddress = ethers.verifyMessage(message, signature)
						// 提交到后台
						let arr = await api(['Bindgithub', { address: recoveredAddress, message: message, signature: signature }])
						console.log(arr)
						if (arr.code == 200) {
							this.$message.success('绑定成功')
							await automaticLogin()
						} else {
							this.$message.error(arr.data)
						}
						// 解签
						// 发送到后台解签
						// 流程 登录  后端生成一个密码    然后前端使用后端的密码签名   然后发送给登录  后端解密
					} catch (error) {
						this.$message.error('签名失败')
					}
				}
				this.loadingadd = false
			},
		},
		mounted() {
			// 生命周期:

			this.form = { ...this.user }
		},
		watch: {
			mapboxMap1(newData, oldData) {
				this.form = { ...newData }
			},
		},
	}
</script>
<style></style>
<style scoped>
	.setting .el-input {
		width: 300px;
	}
	.setting .el-textarea {
		width: 500px;
	}
	.avatar {
		width: 60px;
		height: 60px;
	}
	.image-slot {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 60px;
		height: 60px;
		background: var(--el-fill-color-light);
		color: var(--el-text-color-secondary);
		font-size: 30px;
	}
	.helf {
		height: 100%;
	}
	@media screen and (max-width: 860px) {
		.setting .el-input {
			width: 2rem;
		}
		.setting .el-textarea {
			width: 2.55rem;
		}
	}
</style>
